import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:hygf/http/file_transfer/down_cap.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../http/DioClient.dart';
import '../../res/my_colors.dart';
import '../../util/LoadingUtils.dart';
import '../../util/log_util.dart';

class UpdateDialog extends StatefulWidget {
  BuildContext parentContext;
  String title;
  String content;
  String url;
  Function()? cancelListener;
  bool force = false;
  bool autoUpload;
  String version;

  UpdateDialog(
      {super.key,
      required this.parentContext,
      required this.url,
      this.title = "发现新版本",
      this.content = "发现新版本，是否更新",
      this.version = "",
      this.cancelListener,
      required this.force,
      required this.autoUpload});

  @override
  _UpdateDialogState createState() => _UpdateDialogState();
}

class _UpdateDialogState extends State<UpdateDialog> {
  double progress = 0.0;
  CancelToken? cancelToken;

  bool uploading = false;
  bool error = false;

  @override
  void initState() {
    if (widget.autoUpload) {
      upload();
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          return !widget.force;
        },
        child: Container(
          height: 150,
          width: double.infinity,
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(16))),
          margin: EdgeInsets.all(8),
          child: Stack(
            children: [
              Positioned(
                  top: 16,
                  left: 16,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        widget.title + widget.version,
                        style: TextStyle(color: Colors.black87, fontSize: 20),
                      ),
                      Text(
                        widget.content,
                        style: TextStyle(color: Colors.black54, fontSize: 16),
                      ),
                    ],
                  )),
              Positioned(
                  left: 0,
                  right: 0,
                  bottom: 0,
                  child: Flex(
                    direction: Axis.horizontal,
                    children: _getBtns(),
                  )),
              Positioned(
                  left: 0,
                  right: 0,
                  bottom: 48,
                  child: LinearProgressIndicator(
                    value: progress,
                    color: MyColors.accent,
                  ))
            ],
          ),
        ));
  }

  void upload() async {
    if (error) {
      Navigator.pop(context);
      DioClient().checkVersion(widget.parentContext, false, autoUpload: true);
      return;
    }

    if (!Platform.isAndroid) {
      LoadingUtils.showError("暂不支持应用内升级");
      Navigator.pop(context);
      return;
    }

    bool hasPermission = await _getStoragePermission();
    if (!hasPermission) {
      LoadingUtils.showError("请授权");
      return;
    }
    setState(() {
      uploading = true;
    });
    var extPath = await getExternalCacheDirectories();
    if (extPath == null || extPath.isEmpty) {
      LoadingUtils.showError("该设备没有可存储文件的目录，无法下载升级");
      return;
    }

    var apkPath = "${extPath[0].path}/hygf/update.apk";

    LogUtil.i("apkPath = ", apkPath);

    cancelToken = CancelToken();
    bool success = await DioClient().down(
        url: widget.url,
        path: apkPath,
        cancelToken: cancelToken,
        onProgress: (_progress) {
          setState(() {
            progress = _progress;
          });
        });
    if (success) {
      InstallPlugin.installApk(apkPath).then((result) {
        print("install success :${result['isSuccess']}");
      }).catchError((error) {
        LoadingUtils.showError("安装失败，${error}");
      });
    } else {
      LoadingUtils.showError("下载失败，请重试");
      setState(() {
        uploading = false;
        error = true;
      });
    }
  }

  _getStoragePermission() async {
    //获取当前的权限
    var status = await Permission.storage.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.storage.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  _getBtns() {
    List<Widget> btns = [];
    if (widget.force) {
      btns.add(_getUpBtn());
    } else {
      btns.add(_getCancelBtn());
      btns.add(_getUpBtn());
    }
    return btns;
  }

  _getUpBtn() {
    return Expanded(
      flex: 1,
      child: MaterialButton(
        onPressed: uploading
            ? null
            : () {
                upload();
              },
        height: 48,
        elevation: 0,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(widget.force ? 16 : 0),
                bottomRight: Radius.circular(16))),
        color: Colors.grey.shade200,
        textColor: MyColors.accent,
        disabledTextColor: Colors.grey,
        child: Text(error ? "重试" : "立即升级"),
      ),
    );
  }

  _getCancelBtn() {
    return Expanded(
      flex: 1,
      child: MaterialButton(
        onPressed: () {
          setState(() {
            uploading = false;
          });
          cancelToken?.cancel();
          if (widget.cancelListener != null) {
            widget.cancelListener!();
          }
          Navigator.pop(context);
        },
        height: 48,
        elevation: 0,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(bottomLeft: Radius.circular(16))),
        color: Colors.grey.shade100,
        child: Text("取消"),
      ),
    );
  }
}
